package com.polonium.pageobject.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.AbstractWebDriverEventListener;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WaitWebDriverEventListener extends AbstractWebDriverEventListener {

	private static final long TIME_OUT_IN_SECONDS = 10;

	@Override
	public void beforeClickOn(WebElement element, WebDriver driver) {
//		LOG.debug("beforeClickOn: {} on {}", element.toString(), driver.getCurrentUrl());
		waitForElementDisplayed(element, driver);
		super.beforeClickOn(element, driver);
	}

	@Override
	public void beforeFindBy(By by, WebElement element, WebDriver driver) {
//		LOG.debug("beforeFindBy: {} on {}", by.toString(), driver.getCurrentUrl());
		super.beforeFindBy(by, element, driver);
	}

	private void waitForElementDisplayed(final WebElement element, final WebDriver webDriver) {
		final WebDriverWait webDriverWait = new WebDriverWait(webDriver, TIME_OUT_IN_SECONDS);

		final ExpectedCondition<Boolean> condition = new ExpectedCondition<Boolean>() {
			@Override
			public Boolean apply(final WebDriver driver) {
				return element.isDisplayed();
			}
		};
		webDriverWait.until(condition);
	}
}
